/**
 * Created by YJH on 2018/5/24.
 * 总结：从HomePage页面到四个tab页面的theme传递，与PopularPage页面的theme到cell的传递得出结论。
 * 由组件之间的跳转，通过<Component theme={this.state.theme}/> theme在state中可以被成功获取并渲染，
 * 组件内部的组装，通过<Component theme={this.state.theme}/> theme在state中并不能被立刻获取。
 * 会先调用生命周期的方法componentWillReceiveProps(nextProps)
 * 并通过它去更新state才能达到我们的预期效果。
 * 还有一点就是第一个组件通过<Component {...this.props}/>这种方式传递属性，如果第一个组件有theme属性，在这种传递方式下，
 * 如果后面的组件通过<Component theme={this.state.theme} {...this.props}/> 来传递属性，会导致{...this.props}覆盖theme={this.state.theme}。
 */
import React, {Component} from 'react';
import {
    StyleSheet,
    View,
    Image,
    Dimensions,
    DeviceEventEmitter,
    TouchableOpacity,
} from 'react-native';
import ScrollableTabView, {ScrollableTabBar} from 'react-native-scrollable-tab-view';
import NavigationBarComponent from '../NavigationBarComponent'
import TabPage from './TabPage';
import LanguageDao, {FLAG_LAN} from '../../expand/dao/LanguageDao';
import SearchPage from '../search/SearchPage';
import MoreMenu, {MORE_MENU} from '../../common/MoreMenu';
import NavigationBarUtil from '../../util/NavigationBarUtil';
import {FLAG_TAB} from '../home/HomePage';
import BasePage from '../home/BasePage';


export default class PopularPage extends BasePage {

    constructor(props) {
        super(props);
        // this.itemStateChanged = false;
        this.LanguageDao = new LanguageDao(FLAG_LAN.flagKey);
        this.state = ({
            dataArray: [],
            theme:this.props.hTheme,
        });

    }

    /** view加载完之后就获取存储的标签状态数据 并赋值给 dataArray */
    componentDidMount() {
        super.componentDidMount();
        //组件加载完成之后，注册通之
        // this.listener = DeviceEventEmitter.addListener('popular_itemStateChanged', () => {
        //     this.itemStateChanged = true;
        // });

        this.loadDataFromLanguageDao();
    }

    componentWillUnmount() {
        super.componentWillUnmount();
        this.listener && this.listener.remove();
    }

    componentWillReceiveProps(nextProps) {
        // DeviceEventEmitter.emit('showToast',"=="+nextProps);
    }

    loadDataFromLanguageDao() {
        this.LanguageDao.fetch()
            .then(result => {
                this.setState({
                    dataArray: result,
                });
            }).catch(error => {
            console.log(error);
        })
    }

    moreMenuClick = () => {
        this.refs.moreMenu.open();
    };

    renderMoreMenu() {
        let params = {...this.props, fromPage: FLAG_TAB.flag_popularTab};
        return <MoreMenu
            ref="moreMenu"
            {...params}
            menus={[MORE_MENU.custom_key, MORE_MENU.custom_language, MORE_MENU.remove_key, MORE_MENU.about_author, MORE_MENU.share]}
            anchorView={() => this.refs.moreMenuButton}/>
    }

    /**
     * 功能：右侧的搜索按钮
     * */
    getRightSearchButton() {
        return <View style={{flexDirection: 'row'}}>
            <TouchableOpacity onPress={() => this.props.navigator.push({
                component: SearchPage,
                params: {...this.props},
            })}>
                <Image style={styles.searchButton} source={require('../../../res/images/ic_search_white_48pt.png')}/>

            </TouchableOpacity>
            {NavigationBarUtil.getMoreMenuButton(this.moreMenuClick)}
        </View>
    }

    render() {
        let tabTheme=this.state.theme.themeColor;
        //防止渲染抖动:因为方法render执行在componentDidMount之后，执行到render时由于还是不知道TabPage的数量，无法计算显示渲染长度。
        const tabs = this.state.dataArray.length > 0 ? <ScrollableTabView
            renderTabBar={() => <ScrollableTabBar/>}
            tabBarBackgroundColor={tabTheme}
            tabBarInactiveTextColor='mintcream'
            tabBarActiveTextColor='white'
            tabBarUnderlineStyle={{backgroundColor: 'white', height: 3}}
        >

            {this.state.dataArray.map((result, i, array) => {
                let lan = array[i];
                return lan.checked ? <TabPage key={i} hTheme={this.state.theme} tabLabel={lan.name} {...this.props}/> : null;
            })}
            {/*<TabPage tabLabel="android"/>*/}
            {/*<TabPage tabLabel="ios"/>*/}
            {/*<TabPage tabLabel="java"/>*/}
            {/*<TabPage tabLabel="javascript"/>*/}
            {/*<TabPage tabLabel="python"/>*/}

        </ScrollableTabView> : null;
        return (
            <View style={styles.container}>
                <NavigationBarComponent
                    title={'热门'}
                    style={this.state.theme.styles.navBar}
                    statusBar={{backgroundColor:this.state.theme.themeColor}}
                    rightButton={this.getRightSearchButton()}/>
                {tabs}
                {this.renderMoreMenu()}
            </View>
        )
    }
}

const window = Dimensions.get('window');
const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F5FCFF',
    },
    searchButton: {
        width: 20,
        height: 20,
        margin:5,
        marginLeft: window.width - 60,
        justifyContent:'center'
    },
    boy_text: {
        fontSize: 18,
        color: 'black',
        alignSelf: 'center',
    },
    tab_image: {
        width: 20,
        height: 20,
    },
    text: {
        fontSize: 18,
        marginTop: 10,
        alignSelf: 'center',
    },
    button: {
        height: 60,
        marginTop: 30,
        fontSize: 20,
        alignSelf: 'center',
    },
    edt: {
        height: 50,
        marginTop: 30,
        minWidth: 300,
        alignSelf: 'center',
        borderColor: '#02F78E',
    },
});